package com.lanou3g.bbs.controller;

import com.lanou3g.bbs.entity.User;
import com.lanou3g.bbs.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/userController")
public class UserController {
    @Autowired
    private Service service;

    @RequestMapping("/login")
    public void login(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
        user = service.login(user);
        if (user == null) {
            fieldWrong(request, response, "用户名/密码错误");
        } else {
            response.sendRedirect("/jsps/home.jsp");
        }
    }

    private void fieldWrong(HttpServletRequest request, HttpServletResponse response
            , String msg) throws ServletException, IOException {
        request.setAttribute("msg", msg);
        request.getRequestDispatcher("/msg.jsp").forward(request, response);
    }

    @RequestMapping("/register")
    private void register(User user, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (user.getName().equals("") || user.getPwd().equals("")) {
            fieldWrong(request, response, "注册失败");
            return;
        }
        if (user.getName().contains(" ") || user.getPwd().contains(" ")) {
            fieldWrong(request, response, "注册失败");
            return;
        }
        if (service.register(user)) {
            response.sendRedirect("/jsps/home.jsp");
        } else {
            fieldWrong(request, response, "注册失败");
        }
    }
}
